< previous page page_291 next page >

Page 291
The GROUP BY_HAVING Clause
One of the more powerful SQL clauses is the GROUP BY_HAVING clause. This clause lets you use the SQL aggregate functions discussed earlier today to easily create result sets that contain a list of subtotals of the underlying data table. For example, you might want to be able to create a data set that contains a list of Titles and the total Units sold, by Title. The following SQL statement (see Figure 8.25) can do that:
SELECT Title, SUM(Units) AS UnitsSold
   FROM BookSales
   GROUP BY Title
0291-01.jpg
Figure 8.25.
Using 
GROUP BY to create subtotals.
The GROUP BY clause requires that all numeric columns in the SELECT column list be a part of an SQL aggregate function (SUM, AVG, MIN, MAX, and COUNT). Also, you cannot use the * as part of the SELECT column list when you use the GROUP BY clause.
What if you wanted to get a list of all the book titles that sold more than 100 units for the year? The first thought would be to use a WHERE clause:
SELECT Titles, SUM(Units) AS UnitsSold
   WHERE Sum(Units) > 100
   GROUP BY Units
However, if you try to run this SQL statement, you discover that SQL does not allow aggregate functions within the WHERE clause. You really want to use a WHERE clause after the aggregate function has created a resulting column. In plain English, the query needs to perform the following steps:
· Add up all the units.
· Write the results to a temporary table.
· Display only those rows in the temporary table that have a unit total greater than 100.

 
< previous page page_291 next page >

If you like this book, buy it!